import axios from 'axios';
import { api } from '@/utils/status';
import router from '@/router';
import { ElMessage } from 'element-plus';
import * as storage from '@/utils/storage'
import useAppStore from '@/stores/app';
import useUserStore from '@/stores/user';

// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';

const service = axios.create({
  // 如果环境是线上环境不需要跨域，可以直接配置import.meta.env.VITE_APP_BASE_API为线上地址，所有请求中要手动加上/api
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // baseURL: '/api',
  timeout: 200000
});
let appStore = null,
    userStore = null;

// 请求拦截
service.interceptors.request.use(config => {
  const useToken = (config.headers || {}).useToken === false;
  // 是否需要添加token
  if (!useToken && storage.getToken()) {
    config.headers['Authorization'] = storage.getToken();
  }
  return config;
},
error => {
  return Promise.reject(error);
});

// 响应拦截
service.interceptors.response.use(res => {
  // console.log('源响应：')
  // console.log(res)
  /*
  { data: { code, msg, data }, headers, config, request }
  */
  // 未设置状态码默认成功
  const code = res.data.code || api.code.SUCCESS;
  // 获取响应(错误)信息 - 先使用后端返回的
  const msg = res.data.msg || api.getMsg(code);
  const data = res.data.data || null;
  // 添加全局状态库，获取是否需要权限、角色、过滤路由
  appStore = appStore ? appStore : useAppStore();
  userStore = userStore ? userStore : useUserStore();
  // 二进制文件数据直接返回
  if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer'){
    return data;
  }
  // 未登录 - 清除用户信息缓存跳转登录 todo - 添加登录验证失败的状态码
  if (code === api.code.NOTLOGIN && appStore.hasPromission) {
    // console.log('响应状态未登录')
    userStore.logout()
      .then(() => {
        console.log('登出')
        console.log(router.currentRoute.value.fullPath)
        if (!/^\/login/.test(router.currentRoute.value.fullPath)){
          ElMessage.error(msg);
          const queryStr = Object.keys(router.currentRoute.value.query).reduce((str, key) => str += `&${key}=${router.currentRoute.value.query[key]}`, '');
          console.log(`定向路由： /login?redirect=${router.currentRoute.value.path}${queryStr}`)
          router.replace(`/login?redirect=${router.currentRoute.value.path}${queryStr}`)
        }
      })
    return Promise.reject(new Error(msg));
  } else if (code !== api.code.SUCCESS){
    console.log(`错误状态码: ${code}, 信息: ${msg}`);
    ElMessage({
      type: 'error',
      dangerouslyUseHTMLString: true,
      message: msg,
      duration: 3000
    });
    return Promise.reject(new Error(msg));
  } else {
    // 成功直接返回数据
    return Promise.resolve(data);
  }
},
error => {
  console.log(error)
  let message = error.msg || error.message || '数据响应失败，请稍后重试或联系管理员';
  ElMessage({ message, type: 'error', duration: 5000});
  return Promise.reject(error);
});

export default service;